#!/bin/bash
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/sys_check.sh"
if [ -f /etc/os-release ]; then
   echo "Linux system."
elif [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
   echo "macOS system."
   if [ -f ~/.bash_profile ]; then
      source ~/.bash_profile
    fi
   echo "This app dosen't support macOS."
   exit 1
elif current_os_is_windows; then
   echo "Windows system."
else
   echo "Unknown OS"
fi

APP_INSTALL_NAME="partpacker"
APP_TARGET_DIR_NAME="partpacker"

echo "lmdprogress:3"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_conda.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/conda_run.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/conda_and_pip_settings.sh"
source "$LMD_BASE_INSTALL_SCRIPT_DIR/apps/$APP_INSTALL_NAME/env"

export CURRENT_APP_PATH="${LMD_APPS_DIR}/${APP_TARGET_DIR_NAME}"
echo $CURRENT_APP_PATH
mkdir -p "$CURRENT_APP_PATH"

echo "lmdprogress:8"

if [ -d "$CURRENT_APP_PATH" ]; then
    echo "App Dir: "$CURRENT_APP_PATH
else
    echo "Error, App Dir dose not exist, please retry. "$CURRENT_APP_PATH
    exit 1
fi

echo "lmdprogress:12"

export GIT_HOST=${GITHUB_PROXY}"https://github.com"
export GIT_REPO_URL="${GIT_HOST}/nvlabs/partpacker"


export GIT_REPO_BRANCH="main"
export LOCAL_REPO_PATH="$CURRENT_APP_PATH"
sh "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/git_clone_and_fetch.sh"

echo "lmdprogress:20"

conda --version
echo "lmdprogress:25"
cd "$CURRENT_APP_PATH"

export CONDA_PREFIX="./venv"

if [ -d "$CONDA_PREFIX" ]; then
    echo "found ./venv. remove it. "
    rm -rf "$CONDA_PREFIX"
fi

PYTHON_VER_ENV=3.12
conda_create_env $CONDA_PREFIX python=$PYTHON_VER_ENV -y

echo "lmdprogress:30"

cd "$CURRENT_APP_PATH"


source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_torch_multi_method.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_ffmpeg.sh"

echo "lmdprogress:40"

conda_run_pip_install --upgrade packaging modelscope huggingface_hub hf_xet meshiki

echo "lmdprogress:43"

cd "$CURRENT_APP_PATH"
conda_run_pip_install -r requirements.txt

echo "lmdprogress:70"

if [ -z "$HF_ENDPOINT" ] && [ -n "$HF_MIRROR" ]; then
    export HF_ENDPOINT="$HF_MIRROR"
fi

echo "HF_ENDPOINT--"$HF_ENDPOINT

install_models() {
  echo "start download models"
  export HF_HOME="./tmp_hf_home"
  export U2NET_HOME="./unet_home"
  export TORCH_HOME="./tmp_torch_home"
  conda_run_hf_download nvidia/PartPacker "flow.pt" --repo-type model --revision main

  echo "lmdprogress:72"
  conda_run_hf_download nvidia/PartPacker "vae.pt" --repo-type model --revision main
  
  echo "lmdprogress:75"
  conda_run_hf_download facebook/dinov2-giant --repo-type model --revision main

  echo "lmdprogress:80"

  source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/download_utils.sh"
  download_with_resume "./unet_home/u2net.onnx" "${GIT_HOST}/danielgatis/rembg/releases/download/v0.0.0/u2net.onnx"
  
}

install_models

echo "lmdprogress:100"
